// components/ml-nums/ml-nums.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    num: {
      type: Number,
      default: 0,
    },
    diff: null,
  },

  /**
   * 组件的初始数据
   */
  data: {
    timer: undefined,
    showNum: 0,
  },

  observers: {
    num(num) {
      this.animateToTarget(num);
    },
    diff(diff) {
      if (typeof diff === "number") {
        this.animateToTarget(this.data.num - diff, () => {
          this.triggerEvent('animationend');
        });
      } else {
        this.animateToTarget(this.data.num);
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    animateToTarget(targetNum, end) {
      let { showNum } = this.data;
      clearInterval(this.data.timer);
      // 不用触发界面更新时，可以直接赋值
      this.data.timer = setInterval(() => {
        if (showNum === targetNum) {
          clearInterval(this.data.timer);
          if (end) {
            end()
          }
          return;
        }
        let diff = Math.floor(Math.abs(targetNum - showNum) / 10);
        if (diff < 20) {
          diff = Math.abs(targetNum - showNum);
        }
        showNum += showNum < targetNum ? diff : -diff;
        this.setData({ showNum })
      }, 16)
    }
  }
})